package com.github.pig.admin.controller.repair;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.entity.SysDict;
import com.github.pig.admin.model.entity.SysFile;
import com.github.pig.admin.model.repair.RepairRecord;
import com.github.pig.admin.model.repair.RepairRecordWhere;
import com.github.pig.admin.service.bindowner.BindOwnerService;
import com.github.pig.admin.service.dict.SysDictService;
import com.github.pig.admin.service.repair.IRepairRecordService;
import com.github.pig.admin.service.sysFile.SysFileService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 报修记录表 前端控制器
 * </p>
 *
 * @author lxm
 * @since 2018-06-27
 */
@RestController
@RequestMapping("/repairRecord")
public class RepairRecordController extends BaseController {
    @Autowired
    private IRepairRecordService repairRecordService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private BindOwnerService bindOwnerService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return RepairRecord
    */
    @GetMapping("/{id}")
    public AjaxJson get(@PathVariable(value = "id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String,Object> map = new HashMap<>();
        List<Map<String,String>> base64 = new ArrayList<>();
        List<Map<String,String>> base64Result = new ArrayList<>();
        ajaxJson.setSuccess(true);
        try{
            RepairRecord repairRecord = repairRecordService.selectById(id);
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("type","repair_status");
            entityWrapper.eq("value",repairRecord.getStatus());
            SysDict sysDict = sysDictService.selectOne(entityWrapper);
            if(sysDict!=null){
                repairRecord.setStatusName(sysDict.getLabel());
            }
            //获取报修图片
            EntityWrapper fileWrapper = new EntityWrapper();
            fileWrapper.eq("relation_id",id);
            fileWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
            fileWrapper.eq("remarks",CommonConstant.REPAIR_IMG);
            //获取文件列表
            List<SysFile> sysFiles = sysFileService.selectList(fileWrapper);
            //获取报修维修结果图片
            EntityWrapper fileResultWrapper = new EntityWrapper();
            fileResultWrapper.eq("relation_id",id);
            fileResultWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
            fileResultWrapper.eq("remarks",CommonConstant.REPAIR_IMG_RESULT);
            //获取文件列表
            List<SysFile> sysResultFiles = sysFileService.selectList(fileResultWrapper);
            setBase64Map(base64,sysFiles);
            ajaxJson.setObj(repairRecord);
            map.put("imgs",base64);
            setBase64Map(base64Result,sysResultFiles);
            map.put("imgsResult",base64Result);
            ajaxJson.setAttributes(map);
        }catch(Exception e){
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("发生异常!");
        }

        return ajaxJson;
    }

    private void setBase64Map(List<Map<String, String>> base64, List<SysFile> sysFiles)throws  Exception{
        for(SysFile sf:sysFiles){
            Map<String,String> imgMap = new HashMap<>();
            imgMap.put("id",sf.getId());
            imgMap.put("data",sf.getDocPath());
            base64.add(imgMap);
        }
    }


    /**
    * 获取个人维修记录
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params,RepairRecordWhere repairRecordWhere) {
        //当前登陆名
        String loginName = getUserName();
        UserVO vo = bindOwnerService.selectUserVoByUsername(loginName);
        EntityWrapper entityWrapper = new EntityWrapper();
        initCondition(vo,repairRecordWhere,entityWrapper);
        Page<RepairRecord> page = new Page<RepairRecord>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        entityWrapper.setSqlSelect("id,start_time AS startTime,end_time AS endTime,lift_user AS liftUser,lift_user_name as liftUserName,STATUS,(select label from sys_dict where type='repair_status' and value=status) as statusName,img_path AS imgPath,description,repair_user AS repairUser,(select realname from sys_user where user_id=repair_user) as repairUserName,repair_result AS repairResult,position,accept_time AS acceptTime,accept_user AS acceptUser,(select realname from sys_user where user_id=accept_user) as acceptUserName,bz,result_img AS resultImg,operation_description AS operationDescription,house_id AS houseId,unit_id AS unitId,community_id AS communityId,building_id AS buildingId,del_flag AS delFlag,appraise_result AS appraiseResult,(select label from sys_dict where type='satisfaction' and value=repair_result) as repairResultName,appraise");
        return repairRecordService.selectPage(page,entityWrapper);
    }

    private void initCondition(UserVO vo, RepairRecordWhere repairRecordWhere,EntityWrapper entityWrapper) {
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("community_id",repairRecordWhere.getCommunityId());
        //如果登陆人既是物业人员又是业主，判断app选择的身份
        if(StringUtils.isEmpty(repairRecordWhere.getType())){
            vo.setType(CommonConstant.USER_TYPE_OWNER);
        }
        //判断当前登陆人身份
        if(vo.getType().equals(CommonConstant.USER_TYPE_MANAGER)){
            //经理 可查看所有单据 待办任务查看自己
            if(CommonConstant.DONE.equals(repairRecordWhere.getType())){
                //查看已办记录
                entityWrapper.eq("repair_user",vo.getUserId());
                entityWrapper.ge("status",CommonConstant.REPAIR_STATUS_END);
            }if(CommonConstant.TO_DONE.equals(repairRecordWhere.getType())){
                //查看待办记录
                entityWrapper.eq("repair_user",vo.getUserId());
                entityWrapper.eq("status",CommonConstant.REPAIR_STATUS_ASSIGN);
            }else{
                entityWrapper.eq("lift_user",vo.getUserId());
            }
        }else if(vo.getType().equals(CommonConstant.USER_TYPE_SERVICE)){
            //客服 查看提交的单据 和自己受理的单据
            if(CommonConstant.DONE.equals(repairRecordWhere.getType())){
                //查看已办记录
                entityWrapper.eq("accept_user",vo.getUserId());
                entityWrapper.ge("status",CommonConstant.REPAIR_STATUS_ACCEPT);
            }else if(CommonConstant.TO_DONE.equals(repairRecordWhere.getType())){
                //查看待办记录
                entityWrapper.eq("status","0");
            }
        }else if(vo.getType().equals(CommonConstant.USER_TYPE_ENGINEERING)){
            //工程  只需查看配发给自己的单据
            entityWrapper.eq("repair_user",vo.getUserId());
            if(CommonConstant.DONE.equals(repairRecordWhere.getType())){
                //查看已办记录
                entityWrapper.ge("status",CommonConstant.REPAIR_STATUS_END);
            }else if(CommonConstant.TO_DONE.equals(repairRecordWhere.getType())){
                //查看待办记录
                entityWrapper.eq("status",CommonConstant.REPAIR_STATUS_ASSIGN);
            }

        }else if(vo.getType().equals(CommonConstant.USER_TYPE_OWNER)){
            //业主 查看自己提交的记录
            entityWrapper.eq("lift_user",vo.getUserId());
        }
        entityWrapper.orderBy("start_time",false);
    }

    /**
     * 业主新增报修记录
     * @param  repairRecord  实体
     * @return success/false
     */
    @RequestMapping("/addOwner")
    public R<Boolean> add(@RequestBody RepairRecord repairRecord) {
        repairRecord.setDelFlag(CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotBlank(repairRecord.getStatus())){
            //当前登陆名
            Claims claims = getCurrentUserInfo();
            String loginName = (String) claims.get("user_name");
            UserVO vo = bindOwnerService.selectUserVoByUsername(loginName);
            repairRecord.setAcceptUser(vo.getUserId()+"");
            repairRecord.setAcceptTime(new Date());
            repairRecord.setStatus(repairRecord.getStatus());//提交状态
        }else{
            repairRecord.setStatus("0");//提交状态
        }
        repairRecord.setStartTime(new Date());
        return new R<>(repairRecordService.insert(repairRecord));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable String id) {
        RepairRecord repairRecord = new RepairRecord();
        repairRecord.setId(id);
        repairRecord.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(repairRecordService.updateById(repairRecord));
    }

    /**
     * 评价
     * @param  repairRecord  实体
     * @return success/false
     */
    @PutMapping
    public R<Boolean> edit(@RequestBody RepairRecord repairRecord) {
        repairRecord.setStatus("4");
        return new R<>(repairRecordService.updateById(repairRecord));
    }

    /**
     * 工程人员提交维修结果信息
     * @param repairRecord
     * @return
     */
    @RequestMapping("/repairAfter")
    public R<Boolean> repairAfter(@RequestBody RepairRecord repairRecord) {
        repairRecord.setStatus(CommonConstant.REPAIR_STATUS_END);
        repairRecord.setEndTime(new Date());
        return new R<>(repairRecordService.updateById(repairRecord));
    }

    /**
     * 上传图片保存本地
     * @param modelMap
     * @param request
     * @param type
     * @param path
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public AjaxJson upload(ModelMap modelMap, HttpServletRequest request, String type,@Value("${upload.path}")String path) throws IOException {
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //存储名称ID
        String relationId = UUID.randomUUID().toString().replaceAll("-","");
        List<SysFile> sysFileList = new ArrayList<>();
        //当前登陆名
        Claims claims = getCurrentUserInfo();
        String loginName = (String) claims.get("user_name");
        Map<String,Object> map = new HashMap<>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            try {
                //年月日
                String time = DateFormatUtils.format(new Date(),"yyyyMMdd");
                String real =path+"/images/"+type+ File.separator+time;
                File realfile = new File(real);

                //创建目录
                if(!realfile.exists()){
                    realfile.mkdirs();
                }
                //存储名称ID
                String id = UUID.randomUUID().toString().replaceAll("-","");
                String from_file_name = file.getOriginalFilename();
                String ext = FilenameUtils.getExtension(from_file_name);
                File save_File = new File(realfile,id+"."+ext);
                //保存到新文件中
                inputStream = file.getInputStream();
                outputStream = new FileOutputStream(save_File);
                FileCopyUtils.copy(inputStream,outputStream);
                //保存数据库
                SysFile sysFile = new SysFile();
                sysFile.setCreateDate(new Date());
                sysFile.setCreateBy(loginName);
                sysFile.setDelFlag(CommonConstant.STATUS_NORMAL);
                sysFile.setDocType(ext);
                sysFile.setDocPath(realfile+"/"+id+"."+ext);
                sysFile.setRelationId(relationId);
                sysFileList.add(sysFile);
            } catch (Exception e) {
                j.setSuccess(false);
            }finally{
                if(outputStream!=null){
                    outputStream.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            }
        }
        map.put("relationId",relationId);
        j.setAttributes(map);
        if(sysFileList!=null&&sysFileList.size()>0){
            sysFileService.insertBatch(sysFileList);
            j.setObj(sysFileList.get(0).getId());
        }
        return j;
    }

    @RequestMapping("/showImg")
    public List<Map<String,String>>  showImg(HttpServletRequest request, HttpServletResponse response,String id,String type) {
        List<Map<String,String>> base64 = new ArrayList<>();
        try{
            if(StringUtils.isEmpty(id)){
                return null;
            }
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("relation_id",id);
            entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
            if(StringUtils.isNotBlank(type)){
                entityWrapper.eq("remarks",type);
            }
            //获取文件列表
            List<SysFile> sysFiles = sysFileService.selectList(entityWrapper);
            List<String> filePaths = new ArrayList<>();
            if (sysFiles.size() > 0){
                for (SysFile sysFile : sysFiles) {
                    filePaths.add(sysFile.getDocPath());
                }

            }
            //setBase64Map(base64,sysFiles);
        }catch(Exception e){
            return null;
        }
        return base64;
    }

    /**
     * 删除-报修图片
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/deleteImg")
    public R<Boolean> deleteImg(String id) {
        SysFile sysFile = new SysFile();
        sysFile.setId(id);
        sysFile.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(sysFileService.updateById(sysFile));
    }



}
